<template>
  <div class="patient-info-tab">
    <!-- 患者基本信息 -->
    <van-cell-group inset title="基本信息" class="info-section">
      <template v-if="isLoading">
        <div class="skeleton-block" v-for="i in 7" :key="i"></div>
      </template>
      <template v-else>
        <van-cell title="姓名" :value="patientInfo.name" />
        <van-cell title="性别" :value="patientInfo.gender === 1 ? '男' : patientInfo.gender === 2 ? '女' : '未知'" />
        <van-cell title="年龄" :value="calculateAge(patientInfo)" />
        <van-cell title="身份证" :value="patientInfo.idCard" />
        <van-cell title="出生日期" :value="formatBirthDate(patientInfo.birthDate)" />
        <van-cell title="联系电话" :value="patientInfo.phone" />
        <van-cell title="现住址" :value="patientInfo.address" />
      </template>
    </van-cell-group>
    
    <!-- 就诊信息 -->
    <van-cell-group inset title="就诊信息" class="info-section">
      <template v-if="isLoading">
        <div class="skeleton-block" v-for="i in 9" :key="i"></div>
      </template>
      <template v-else>
        <van-cell title="就诊号" :value="visitInfo.visitNo" />
        <van-cell title="就诊科室" :value="getDepartmentName()" />
        <van-cell title="就诊医生" :value="getDoctorName()" />
        <van-cell title="就诊类型" :value="formatVisitType(visitInfo.visitType)" />
        <van-cell title="主诉" :value="visitInfo.chiefComplaint" />
        <van-cell title="现病史" :value="visitInfo.presentIllness" />
        <van-cell title="就诊时间" :value="formatDate(visitInfo.visitTime)" />
        <van-cell title="入院时间" :value="formatDate(visitInfo.admissionTime)" />
        <van-cell title="出院时间" :value="formatDate(visitInfo.dischargeTime) || '未出院'" />
      </template>
    </van-cell-group>
    
    <!-- 生命体征 -->
    <van-cell-group inset title="生命体征" class="info-section">
      <template v-if="isLoading">
        <div class="skeleton-block" v-for="i in 7" :key="i"></div>
      </template>
      <template v-else>
        <van-cell title="身高" :value="formatVitalSign(vitalSigns.height, 'cm')" />
        <van-cell title="体重" :value="formatVitalSign(vitalSigns.weight, 'kg')" />
        <van-cell title="体温" :value="formatVitalSign(vitalSigns.temperature, '°C')" />
        <van-cell title="脉搏" :value="formatVitalSign(vitalSigns.pulse, '次/分')" />
        <van-cell title="收缩压" :value="formatVitalSign(vitalSigns.systolicPressure, 'mmHg')" />
        <van-cell title="舒张压" :value="formatVitalSign(vitalSigns.diastolicPressure, 'mmHg')" />
        <van-cell title="测量时间" :value="formatDate(vitalSigns.measureTime)" />
      </template>
    </van-cell-group>
    
    <!-- 生命体征趋势图 -->
    <van-cell-group inset title="生命体征趋势" class="info-section">
      <template v-if="isLoading">
        <div class="skeleton-chart"></div>
      </template>
      <template v-else>
        <div class="chart-container" ref="chartContainer"></div>
        
        <div class="chart-legend">
          <div class="legend-item">
            <div class="legend-color legend-color-temperature"></div>
            <div class="legend-text">体温</div>
          </div>
          <div class="legend-item">
            <div class="legend-color legend-color-pulse"></div>
            <div class="legend-text">脉搏</div>
          </div>
          <div class="legend-item">
            <div class="legend-color legend-color-systolic"></div>
            <div class="legend-text">收缩压</div>
          </div>
          <div class="legend-item">
            <div class="legend-color legend-color-diastolic"></div>
            <div class="legend-text">舒张压</div>
          </div>
        </div>
      </template>
    </van-cell-group>
    
    <!-- 历史生命体征按钮 -->
    <div class="history-btn-container" v-if="!isLoading">
      <van-button type="primary" round block @click="showHistoryVitalSigns">
        查看历史生命体征
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue';
import { showToast } from 'vant';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必要的组件
echarts.use([LineChart, GridComponent, TitleComponent, TooltipComponent, LegendComponent, CanvasRenderer]);

const props = defineProps({
  patientId: {
    type: [String, Number],
    required: true
  },
  patientInfo: {
    type: Object,
    required: true
  },
  visitInfo: {
    type: Object,
    required: true
  },
  vitalSigns: {
    type: Object,
    required: true
  },
  recentVitalSigns: {
    type: Array,
    required: true
  },
  isLoading: {
    type: Boolean,
    default: false
  }
});

const chartContainer = ref(null);
let chart = null;

// 计算年龄
const calculateAge = (patient) => {
  if (!patient.birthDate) return '';
  
  try {
    const birthYear = parseInt(patient.birthDate.substring(0, 4));
    const currentYear = new Date().getFullYear();
    return `${currentYear - birthYear}岁`;
  } catch (e) {
    return '';
  }
};

// 格式化出生日期
const formatBirthDate = (birthDate) => {
  if (!birthDate) return '';
  
  try {
    const year = birthDate.substring(0, 4);
    const month = birthDate.substring(4, 6);
    const day = birthDate.substring(6, 8);
    return `${year}-${month}-${day}`;
  } catch (e) {
    return birthDate;
  }
};

// 格式化就诊类型
const formatVisitType = (type) => {
  const typeMap = {
    1: '门诊',
    2: '急诊',
    3: '住院'
  };
  return typeMap[type] || '未知';
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (e) {
    return dateStr;
  }
};

// 格式化生命体征数据
const formatVitalSign = (value, unit) => {
  if (value === undefined || value === null) return '';
  return `${value} ${unit}`;
};

// 获取科室名称
const getDepartmentName = () => {
  return props.visitInfo.departmentName || '';
};

// 获取医生姓名
const getDoctorName = () => {
  return props.visitInfo.doctorName || '';
};

// 查看历史生命体征
const showHistoryVitalSigns = () => {
  showToast('历史生命体征功能开发中');
};

// 初始化图表
const initChart = async () => {
  if (!chartContainer.value) return;
  
  // 销毁旧图表
  if (chart) {
    chart.dispose();
    chart = null;
  }
  
  // 等待DOM更新完成
  await nextTick();
  
  try {
    // 创建新图表
    chart = echarts.init(chartContainer.value, null, {
      renderer: 'canvas',
      useDirtyRect: false
    });
    
    // 设置图表选项
    updateChart();
  } catch (error) {
    console.error('图表初始化失败:', error);
  }
};

// 更新图表数据
const updateChart = () => {
  if (!chart || !props.recentVitalSigns || props.recentVitalSigns.length === 0) return;
  
  try {
    // 准备数据
    const dates = [];
    const temperatures = [];
    const pulses = [];
    const systolicPressures = [];
    const diastolicPressures = [];
    
    // 对数据按时间排序
    const sortedData = [...props.recentVitalSigns].sort((a, b) => {
      return new Date(a.measureTime) - new Date(b.measureTime);
    });
    
    // 提取数据
    sortedData.forEach(item => {
      const dateStr = formatDate(item.measureTime).split(' ')[0];
      dates.push(dateStr);
      temperatures.push(item.temperature);
      pulses.push(item.pulse);
      systolicPressures.push(item.systolicPressure);
      diastolicPressures.push(item.diastolicPressure);
    });
    
    // 设置图表选项
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '体温',
          min: function(value) {
            return Math.floor(value.min - 0.5);
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666',
            fontSize: 12,
            formatter: '{value} °C'
          }
        },
        {
          type: 'value',
          name: '其他',
          axisLine: {
            show: true,
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666',
            fontSize: 12
          }
        }
      ],
      series: [
        {
          name: '体温',
          type: 'line',
          yAxisIndex: 0,
          data: temperatures,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#ff9800'
          },
          lineStyle: {
            width: 2
          }
        },
        {
          name: '脉搏',
          type: 'line',
          yAxisIndex: 1,
          data: pulses,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#2196f3'
          },
          lineStyle: {
            width: 2
          }
        },
        {
          name: '收缩压',
          type: 'line',
          yAxisIndex: 1,
          data: systolicPressures,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#4caf50'
          },
          lineStyle: {
            width: 2
          }
        },
        {
          name: '舒张压',
          type: 'line',
          yAxisIndex: 1,
          data: diastolicPressures,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#f44336'
          },
          lineStyle: {
            width: 2
          }
        }
      ]
    };
    
    // 安全地设置选项
    chart.setOption(option);
  } catch (error) {
    console.error('更新图表失败:', error);
  }
};

// 添加窗口大小变化的监听
const handleResize = () => {
  chart && chart.resize();
};

// 监听生命体征数据变化，更新图表
watch(() => props.recentVitalSigns, (newVal) => {
  if (newVal && newVal.length && !props.isLoading) {
    nextTick(() => {
      if (chart) {
        updateChart();
      } else {
        initChart();
      }
    });
  }
}, { deep: true });

// 监听加载状态变化
watch(() => props.isLoading, (loading) => {
  if (!loading && props.recentVitalSigns && props.recentVitalSigns.length) {
    nextTick(() => initChart());
  }
});

// 组件挂载后初始化图表
onMounted(() => {
  if (props.recentVitalSigns && props.recentVitalSigns.length && !props.isLoading) {
    initChart();
  }
  
  // 添加窗口大小变化的监听器
  window.addEventListener('resize', handleResize);
});

// 组件卸载前清理图表实例和事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (chart) {
    chart.dispose();
    chart = null;
  }
});
</script>

<style scoped>
.patient-info-tab {
  padding: 0 0 20px 0;
}

.info-section {
  margin-top: 12px;
}

.chart-container {
  height: 250px;
  margin: 12px 0;
}

.chart-legend {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 0 8px 8px 0;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  margin-right: 4px;
}

.legend-text {
  font-size: 12px;
  color: #666;
}

.history-btn-container {
  margin: 16px;
}

/* 骨架屏样式 */
.skeleton-block {
  height: 20px;
  background-color: #f2f3f5;
  margin: 12px 16px;
  border-radius: 4px;
}

.skeleton-chart {
  height: 250px;
  margin: 12px 16px;
  background-color: #f2f3f5;
  border-radius: 8px;
}

.legend-color-temperature {
  background-color: #ff9800;
}

.legend-color-pulse {
  background-color: #2196f3;
}

.legend-color-systolic {
  background-color: #4caf50;
}

.legend-color-diastolic {
  background-color: #f44336;
}
</style> 